import React, { useEffect, useState } from "react";
import { Layout, Menu } from "antd";

import { useSelector } from "react-redux";
import menus from '@/routers'
import { useLocation, useNavigate } from "react-router-dom";
const { Sider } = Layout;

export default function SideMenu() {
  const { collapsed } = useSelector((state) => state.appSlice);
  const navigate=useNavigate()
  const changeUrl = ({ key })=>{ 
    setSelectedKeys([key])
    navigate(key);
  }

  //仅展开当前菜单项
  const rootSubmenuKeys = []
  menus.forEach(item=>{
    item.children && rootSubmenuKeys.push(item.key)
  })
  const onOpenChange = (keys)=>{
    const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === -1);  
    if (rootSubmenuKeys.indexOf(latestOpenKey) === -1) {
      setOpenKeys(keys); 
    } else {
      setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
    }
  }

  //左侧菜单的选中
  const {pathname} = useLocation()
  const [selectedKeys,setSelectedKeys] = useState([pathname])
  const getSubMenu = pathname => {
    const pathArray = pathname.split('/').slice(1)
    const arr = pathArray.reduce((init,item,index)=>{
      const str = init[index] + '/' + item
      init.push(str)
      return init
    },[''])
    return arr
  }
  const [openKeys,setOpenKeys] = useState(getSubMenu(pathname))
  useEffect(()=>{
    setSelectedKeys([pathname])
    setOpenKeys(getSubMenu(pathname))
  },[pathname])
 
  return (
    <Sider trigger={null} collapsed={collapsed}>
      <div className="logo" />
      <Menu
        id="side-menu"
        theme="dark"
        mode="inline"
        defaultSelectedKeys={["1"]}
        items={menus}
        onClick={changeUrl}
        openKeys={openKeys}
        onOpenChange={onOpenChange}
        selectedKeys={selectedKeys}
      />
    </Sider>
  );
}
